package com.example.springsecurity.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.domain.CorrectShare;
import com.example.springsecurity.domain.ExportScore;
import com.example.springsecurity.domain.ShareProject;
import com.example.springsecurity.domain.TeacherCorrectShare;
import com.example.springsecurity.mapper.ExperimentMapper;
import com.example.springsecurity.security.SecurityUtils;
import com.example.springsecurity.service.AssignExperimentService;
import com.example.springsecurity.service.CollegeService;
import com.example.springsecurity.service.CorrectShareProjectService;
import com.example.springsecurity.utils.ResultBean;
import com.example.springsecurity.utils.convert.Convert;
import com.example.springsecurity.utils.excel.ExcelUtils;
import com.example.springsecurity.utils.ifnull.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CorrectShareProject
 * @Description TODO    批改共享
 * @Author lvyongwei
 * @Date 2020-10-15 16:37
 **/
@Controller
@RequestMapping("/correctShare")
public class CorrectShareProjectController {

    @Autowired
    private CorrectShareProjectService correctShareProjectService;

    @Autowired
    private CollegeService collegeService;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private ExperimentMapper experimentMapper;

    /**
     * 获取负责的共享实验列表
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:correctShare:correctShareProject')")
    @PostMapping("/getAllCorrectShareProject")
    @ResponseBody
    public ResultBean getAllCorrectShareProject(@RequestBody String data){
        /**
         * 获取当前登录用户
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String message = jsonObject.getString("message");
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<ShareProject> shareProjectList = correctShareProjectService.getAllShareProject(userId,message);
            PageInfo<ShareProject> pageInfo = new PageInfo<>(shareProjectList);
            return ResultBean.success("获取共享列表成功",pageInfo);
        }catch (Exception e){
            return ResultBean.error("获取共享列表失败");
        }
    }


    /**
     * 查看批改列表
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:correctShare:getCorrectList')")
    @PostMapping("/getCorrectList")
    @ResponseBody
    public ResultBean getCorrectList(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer projectId = jsonObject.getInteger("projectId");
        String realName = jsonObject.getString("realName");
        Integer correctStatus = jsonObject.getInteger("correctStatus");
        /**
         * 分頁
         */
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<TeacherCorrectShare> teacherCorrectShares = correctShareProjectService.getAllTeacherCorrectShare(projectId,realName,correctStatus);
            PageInfo<TeacherCorrectShare> pageInfo = new PageInfo<TeacherCorrectShare>(teacherCorrectShares);
            return ResultBean.success("获取批改列表成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("获取批改列表失败");
        }
    }


    /**
     * 點擊批改按鈕,返回提交信息
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:correctShare:correctShare')")
    @PostMapping("/correctShare")
    @ResponseBody
    public ResultBean correctShare(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer submitId = jsonObject.getInteger("submitId");
        try{
            CorrectShare correctShare = correctShareProjectService.getCorrectShare(submitId);
            return ResultBean.success("获取成绩成功",correctShare);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("获取成绩失败");
        }
    }


    /**
     * 提交批改结果
     * @param teacherCorrectShare
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:correctShare:correctShare')")
    @PostMapping("/correctResult")
    @ResponseBody
    public ResultBean correctResult(@RequestBody TeacherCorrectShare teacherCorrectShare){
        try{
            correctShareProjectService.insertCorrectShare(teacherCorrectShare);
            return ResultBean.success("批改成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("批改失败");
        }
    }


    /**
     * 查看批改结果
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:correctShare:lookCorrect')")
    @PostMapping("/lookCorrect")
    @ResponseBody
    public ResultBean lookCorrect(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer correctId = jsonObject.getInteger("correctId");
        try{
            TeacherCorrectShare teacherCorrectShare = correctShareProjectService.getTeacherCorrectShareById(correctId);
            return ResultBean.success("获取批改详情成功",teacherCorrectShare);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("获取批改详情失败");
        }
    }


    /**
     * 导出布置成绩
     * @param request
     * @param response
     * @param projectId
     */
    @GetMapping("/exportScore")
    public void exportScore(HttpServletRequest request, HttpServletResponse response, String projectId) throws IOException {
        ExcelWriter writer = null;
        OutputStream outputStream = response.getOutputStream();
        Integer[] projectIds = Convert.toIntArray(",",projectId);
        try {
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            //String fileName = "导入模板";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode("学生成绩结果","UTF-8")+".xlsx");
            //实例化 ExcelWriter
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
            for(int i=0;i<projectIds.length;i++){
                List<ExportScore> list = correctShareProjectService.exportCorrectShare(projectIds[i]);
                String projectName = experimentMapper.getAssignProject(projectIds[i]).getProjectName();
                /**
                 * 创建标题
                 */
                Table table = new Table(i);
                List<List<String>> headList = new ArrayList<>();
                headList.add(new ArrayList<String>(){{add(projectName);add("学号");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("姓名");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("所属班级");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("总成绩");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("视频成绩");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("实验操作成绩");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("实验报告得分");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("提交时间");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("是否提交");}});
                headList.add(new ArrayList<String>(){{add(projectName);add("是否批改");}});
                table.setHead(headList);
                //实例化表单
                Sheet sheet = new Sheet(i+1,0);
                sheet.setAutoWidth(true);
                sheet.setSheetName("sheet"+i);
                //输出
                writer.write(list, sheet, table);
            }
            writer.finish();
            outputStream.flush();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
